package cn.edu.javaweb.userServlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.javaweb.utils.DBUtil;

@WebServlet("/ForumResponseEditorServlet")
public class ForumResponseEditorServlet extends HttpServlet {
	DBUtil db;
	private static final long serialVersionUID = 1L;
       
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置编码方式
	    request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");   //不设置会乱码
				
		//从ForumResponse.jsp中获取参数
		String answer=request.getParameter("answer");
		String question_id=request.getParameter("id");
		System.out.println(answer);
		
		HttpSession session = request.getSession(true);     // 如果不存在 session 会话，则创建一个 session 对象
		String userid = session.getAttribute("id").toString();  //从session获取id
		
		//JDBC连接数据库
		db = new DBUtil();  //调用构造函数，数据库的搭建
		String SQL = "insert into response (response,user_id,question_id) values ("+"'"+answer+"'"+","+userid+","+question_id+")";
		System.out.println(SQL);
		int result=db.update(SQL);  //调用（工具类）update方法，result来传递结果
	    PrintWriter out=response.getWriter();
		if(result>0){
			response.sendRedirect(request.getContextPath()+"/ForumResponseServlet?id="+question_id+"");
			//out.println("<script language=javascript>alert('留言成功');window.location='ForumResponseServlet?id="+question_id+"';</script>");
	    }else{
	    	out.println("<script language=javascript>alert('留言失败,请重新留言');window.location='ForumResponseServlet?id="+question_id+"';</script>");
		}
	}
}
